#include "websocketserver.h"
#include"debug.h"

WebSocketServer* WebSocketServer::instance = nullptr;


WebSocketServer *WebSocketServer::getInstance()
{
    if(instance == nullptr){
        instance = new WebSocketServer();
    }

    return instance;
}

bool WebSocketServer::init()
{
    bool ok = webSocketServer.listen(QHostAddress::Any, 8089);

    connect(&webSocketServer, &QWebSocketServer::newConnection, this, [=](){
        QWebSocket* socket = webSocketServer.nextPendingConnection();
        qDebug() << "[websocket] New Connection";

        //发送信息
        connect(this, &WebSocketServer::sendTextResp, this, [=]() {
            if (socket == nullptr || !socket->isValid()) {
                LOG() << "socket 对象⽆效!";
                return;
            }

            QByteArray avatar = loadFileToByteArray(":/images/default_avatar.jpg");

            lx::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(lx::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            lx::NotifyNewMessage newMessage;
            lx::MessageInfo messageInfo = makeMessageInfo(this->messageIndex++,"1", avatar);
            newMessage.setMessageInfo(messageInfo);
            notifyMessage.setNewMessageInfo(newMessage);
            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG() << "发送⽂本消息响应" << messageInfo.message().stringMessage().content();
        });

        //删除好友
        connect(this, &WebSocketServer::sendFriendRemove, this, [=]() {
            if (socket == nullptr || !socket->isValid()) {
                LOG() << "socket 对象⽆效!";
                return;
            }
            lx::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(lx::NotifyTypeGadget::NotifyType::FRIEND_REMOVE_NOTIFY);
            lx::NotifyFriendRemove friendRemove;
            QString userId = "1001";
            friendRemove.setUserId(userId);
            notifyMessage.setFriendRemove(friendRemove);
            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG() << "通知对⽅好友通过, userId=" << userId;
        });

        //添加好友
        connect(this, &WebSocketServer::sendFriendApply, this, [=](){
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket 对象无效";
                return;
            }

            lx::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(lx::NotifyTypeGadget::FRIEND_ADD_APPLY_NOTIFY);

            QByteArray avatar = loadImageToByteArray(":/images/default_avatar.jpg");

            lx::NotifyFriendAddApply notifyAdd;
            lx::UserInfo userInfo = makeUserInfo(100, avatar);
            notifyAdd.setUserInfo(userInfo);

            notifyMessage.setFriendAddApply(notifyAdd);
            QByteArray body = notifyMessage.serialize(&serializer);

            socket->sendBinaryMessage(body);
            LOG() << "发送好友申请, userId=" << userInfo.userId();

        });

        //好友申请被同意或拒绝通知
        connect(this, &WebSocketServer::sendFriendProcess, this, [=](bool agree) {
            if (socket == nullptr || !socket->isValid()) {
                LOG() << "socket 对象⽆效!";
                return;
            }
            lx::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(lx::NotifyTypeGadget::NotifyType::FRIEND_ADD_PROCESS_NOTIFY);
            QByteArray avatar = loadImageToByteArray(":/images/default_avatar.jpg");
            lx::NotifyFriendAddProcess friendAddProcess;
            lx::UserInfo userInfo = makeUserInfo(100, avatar);
            friendAddProcess.setAgree(agree);
            friendAddProcess.setUserInfo(userInfo);
            notifyMessage.setFriendProcessResult(friendAddProcess);
            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG() << "通知对⽅好友处理结果, userId=" << userInfo.userId() << ", agree=" << agree;
        });

        //创建新的会话
        connect(this, &WebSocketServer::sendNewChatSession, this, [=]() {
            if (socket == nullptr || !socket->isValid()) {
                LOG() << "socket 对象⽆效!";
                return;
            }
            QByteArray avatar = loadImageToByteArray(":/images/group_avatar.jpg");
            lx::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(lx::NotifyTypeGadget::NotifyType::CHAT_SESSION_CREATE_NOTIFY);
            lx::NotifyNewChatSession newChatSession;
            lx::ChatSessionInfo chatSessionInfo;
            chatSessionInfo.setChatSessionId("2100");
            chatSessionInfo.setSingleChatFriendId("");
            chatSessionInfo.setChatSessionName("新的群聊");
            // bite_im::MessageInfo messageInfo =
            makeEmptyMessageInfo(chatSessionInfo.chatSessionId(), avatar);
            // chatSessionInfo.setPrevMessage(messageInfo);
            chatSessionInfo.setAvatar(avatar);
            newChatSession.setChatSessionInfo(chatSessionInfo);
            notifyMessage.setNewChatSessionInfo(newChatSession);
            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG() << "通知新增消息会话, chatSessionId=" <<chatSessionInfo.chatSessionId();
        });

        connect(socket, &QWebSocket::disconnected, this, [=](){
            qDebug() << "[webSocket] Disconnected";

            //解除信号关联
            disconnect(this, &WebSocketServer::sendTextResp, this, nullptr);
            disconnect(this, &WebSocketServer::sendFriendRemove, this, nullptr);
            disconnect(this, &WebSocketServer::sendFriendApply, this, nullptr);
            disconnect(this, &WebSocketServer::sendFriendProcess, this, nullptr);
            disconnect(this, &WebSocketServer::sendNewChatSession, this, nullptr);

            socket->deleteLater();
        });

        connect(socket, &QWebSocket::errorOccurred, this, [=](QAbstractSocket::SocketError error){
            qDebug() << "[websocket] error: " << error;
        });

        connect(socket, &QWebSocket::textMessageReceived, this, [=](const QString& message){
            qDebug() << "[webSocket] Received message: " << message;

            if(message == "ping"){
                socket->sendTextMessage("pong");
                return;
            }
        });
    });
    return ok;
}
